<?php

namespace App\Console\Commands\Cruise;

use App\Console\Commands\OpenShop\ImportHistoryOrder;
use App\Console\Commands\Traits\ExcelCommandTrait;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Library\FeiShu\SendFs;
use App\Models\Cruise\CruiseProjectCategoryModel;
use App\Models\Cruise\CruiseTaskProjectModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Service\BaseService;
use App\Service\Cruise\CruiseProject\CruiseProjectParam;
use App\Service\Cruise\CruiseProject\CruiseProjectService;
use App\Service\Cruise\CruiseTemplate\CruiseTemplateService;
use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderExecute;
use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderParam;
use App\Support\CustomForm\AttributeSupport;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;


class ImportCollegeExam extends Command
{
    use ExcelCommandTrait;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cruise:import-college-exam';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入商学院试卷';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $url = 'https://file.51kuafu.com/39/08/3bc1033f411eb5661fe3b50ad4bf555361e40f0d5b667e835678a1a41a68.xlsx';

        $this->excelImport(Import::class, $url);
    }
}

class Import
{
    private array $titles = [
        "标签",
        "否决项(是：试题不合格时，考卷得0分）",
        "*题型",
        "*题干",
        "正确答案（多个用英文;隔开）",
        "选项A",
        "选项B",
        "选项C",
        "选项D",
        "选项E",
        "选项F",
        "选项G",
    ];

    private int                  $categoryId;
    private string               $inputType;
    private string               $projectName;
    private array                $options     = [];
    private array                $answerCorrectArr;
    private array                $selectProjectIds;
    private ?CruiseTemplateModel $template;
    private array                $keyToOption = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];

    const PROJECT_SCORE = 5; // 每题分值

    public function collection(Collection $collection, ?Command $command)
    {
        $this->template = CruiseTemplateModel::query()
                                             ->where('sysTemplate', CruiseTemplateModel::SYS_TEMPLATE_COLLEGE)
                                             ->where('status', CruiseTemplateModel::STATUS_ON)
                                             ->orderByDesc('id')
                                             ->first();
        if (!$this->template) {
            $this->throwErr("未配置商学院试卷对应模板", 0);
        }

        $params = $collection
            ->first()
            ->map(function ($item, $row) {

                $itemArr = array_slice($item->toArray(), 0, 12);

                if ($row == 0) {

                    // 表头校验
                    if ($itemArr != $this->titles) {
                        dump($item);
                        dump($this->titles);
                        $this->throwErr('表头错误', $row);
                    }

                    return null;
                }

                // 参数校验
                list($categoryName, $_, $projectTypeText, $projectName, $answerCorrect, $answerA, $answerB, $answerC, $answerD, $answerE, $answerF, $answerG) = $itemArr;

                if (!$categoryName) {
                    return null;
                }

                $categoryId = Cache::store('array')
                                   ->remember("ImportCollegeExam:category:{$categoryName}", 999,
                                       function () use ($categoryName) {
                                           return CruiseProjectCategoryModel::query()
                                                                            ->where('name', $categoryName)
                                                                            ->value('id') ?? 0;
                                       });
                if (!$categoryId) {
                    $this->throwErr("标签错误：{$categoryName}", $row);
                }

                switch ($projectTypeText) {
                    case "判断":

                        if (!in_array($answerCorrect, ['对', '错'])) {
                            $this->throwErr("判断题只能是对错：{$answerCorrect}", $row);
                        }

                        break;
                    case "单选":
                        if (strlen($answerCorrect) > 1) {
                            $this->throwErr("单选题只能选一个：{$answerCorrect}", $row);
                        }

                        $answerCorrectArr = explode(";", $answerCorrect);
                        foreach ($answerCorrectArr as $ans) {

                            $answerKey = "answer" . $ans;
                            if ($$answerKey == '') {
                                $this->throwErr("正确答案：{$ans}，未配置选项", $row);
                            }
                        }

                        break;

                    case "多选":
                        $answerCorrectArr = explode(";", $answerCorrect);
                        if (count($answerCorrectArr) <= 1) {
                            $this->throwErr("多选题至少2个选项：{$answerCorrect}", $row);
                        }

                        if (count($answerCorrectArr) > self::PROJECT_SCORE) {
                            $this->throwErr("多选题最多".self::PROJECT_SCORE."个选项：{$answerCorrect}", $row);
                        }

                        foreach ($answerCorrectArr as $ans) {

                            $answerKey = "answer" . $ans;
                            if ($$answerKey == '') {
                                $this->throwErr("正确答案：{$ans}，未配置选项", $row);
                            }
                        }

                        break;

                    default:
                        $this->throwErr("题型错误：{$projectTypeText}", $row);
                }


                return $itemArr;
            });

        // 操作导入
        $params->filter()
               ->each(function ($param, $row) {

                   // 参数校验
                   list($categoryName, $_, $projectTypeText, $this->projectName, $answerCorrect, $answerA, $answerB, $answerC, $answerD, $answerE, $answerF, $answerG) = $param;

                   switch ($projectTypeText) {
                       case "判断":
                       case "单选":
                           $this->inputType = AttributeSupport::INPUT_TYPE_SELECT;
                           break;
                       case "多选":
                           $this->inputType = AttributeSupport::INPUT_TYPE_SELECT_MULTIPLE;
                           break;
                       default:
                           $this->throwErr("题型错误：{$projectTypeText}", $row);
                   }


                   $this->categoryId = Cache::store('array')
                                            ->remember("ImportCollegeExam:category:{$categoryName}", 999,
                                                function () use ($categoryName) {
                                                    return CruiseProjectCategoryModel::query()
                                                                                     ->where('name', $categoryName)
                                                                                     ->value('id') ?? 0;
                                                });

                   $this->answerCorrectArr = explode(";", $answerCorrect);

                   $totalScore = self::PROJECT_SCORE;

                   $correctFlag  = 1;
                   $consumeScore = 0;

                   $this->options = [];

                   if ($projectTypeText == '判断') {

                       $this->options = [
                           [
                               'text'  => $text = "对",
                               'value' => 1,
                               'score' => $answerCorrect == $text ? self::PROJECT_SCORE : 0,
                           ],
                           [
                               'text'  => $text = "错",
                               'value' => 2,
                               'score' => $answerCorrect == $text ? self::PROJECT_SCORE : 0,
                           ]
                       ];
                   } else {

                       foreach ([$answerA, $answerB, $answerC, $answerD, $answerE, $answerF, $answerG] as $k => $text) {

                           if ($text === null) {
                               continue;
                           }

                           $score = 0;


                           if (in_array($this->keyToOption[$k] ?? '', $this->answerCorrectArr)) {
                               if ($this->inputType == AttributeSupport::INPUT_TYPE_SELECT) {
                                   $score = $totalScore;
                               }

                               if ($this->inputType == AttributeSupport::INPUT_TYPE_SELECT_MULTIPLE) {

                                   if ($correctFlag == count($this->answerCorrectArr)) {
                                       $score = $totalScore - $consumeScore;
                                   } else {
                                       $score        = 1;
                                       $consumeScore += $score;
                                       $correctFlag++;
                                   }
                               }
                           }

                           $this->options[] = [
                               'text'  => $text,
                               'value' => $k + 1,
                               'score' => $score,
                           ];
                       }

                       // 检查score总分
                       $tScore = collect($this->options)->sum('score');
                       if ($tScore != self::PROJECT_SCORE) {
                           $this->throwErr("score总分计算错误", $row);
                       }
                   }

                   // 新增之前校验
                   $projectId = CruiseTaskProjectModel::query()
                                                      ->where('categoryId', $this->categoryId)
                                                      ->where('name', $this->projectName)
                                                      ->where('status', CruiseTaskProjectModel::STATUS_ON)
                                                      ->orderByDesc('id')
                                                      ->value('id');
                   if ($projectId) {
                       $this->selectProjectIds[] = ["projectId" => $projectId, 'inputType' => $this->inputType];
                       dump("row: {$row} projectId: {$projectId}");

                       return;
                   }

                   // 新建project
                   $param = (new CruiseProjectParam())->setCategoryId($this->categoryId)
                                                      ->setName($this->projectName)
                                                      ->setStatus(1)
                                                      ->setInputType($this->inputType)
                                                      ->setOptions($this->options)
                                                      ->setRequired(true);

                   $projectId = (new CruiseProjectService())->addOrEdit($param, 0);

                   $this->selectProjectIds[] = ["projectId" => $projectId, 'inputType' => $this->inputType];
                   dump("row: {$row} projectId: {$projectId}");
               });


        // 更新模板
        $templateBase = [
            "name"        => $this->template->name,
            "desc"        => $this->template->desc,
            "status"      => CruiseTemplateModel::STATUS_ON,
            "sysTemplate" => CruiseTemplateModel::SYS_TEMPLATE_COLLEGE,
            "type"        => CruiseTemplateModel::TYPE_4,
        ];
        $positions    = [
            AttributeSupport::INPUT_TYPE_SELECT          => [
                "positionName" => "单选题",
                "positionId"   => 0,
                "project"      => [],
            ],
            AttributeSupport::INPUT_TYPE_SELECT_MULTIPLE => [
                "positionName" => "多选题",
                "positionId"   => 0,
                "project"      => [],
            ],
        ];

        foreach ($this->selectProjectIds as $val) {
            $positions[$val['inputType']]['project'][] = ['projectId' => $val['projectId']];
        }

        $templateId = (new CruiseTemplateService())
            ->setUserId(0)
            ->setTemplateId($this->template->id)
            ->addOrEdit($templateBase, array_values($positions));

        dump("templateId: {$templateId}");
    }

    private function throwErr(string $msg, int $row)
    {
        $row++;

        throw new \Exception("第{$row}行：" . $msg);
    }
}
